﻿using FZKJ.COMMON;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace FZKJ.ZHXJ.Models
{
    public class FileToEntity
    { 
        /// <summary>
      /// 将上传文件转换成对应的实体列表
      /// </summary>
      /// <typeparam name="T">转换成对应的实体</typeparam>
      /// <param name="context">上下文</param>
      /// <param name="Folder">文件保存的文件夹</param>
      /// <param name="jsonfile">json文件</param>
      /// <param name="file">上传的文件上下文</param>
      /// <returns></returns>
        public static List<T> FileToEntityFunc<T>(HttpContextBase context, string Folder, string jsonfile, HttpPostedFileBase file) where T : class, new()
        {
            string directoryPath = context.Server.MapPath("~/UploadFile/" + Folder + "/");
            if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
            {
                Directory.CreateDirectory(context.Server.MapPath("~/UploadFile/" + Folder + "/"));
            }
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
            file.SaveAs(context.Server.MapPath("~/UploadFile/" + Folder + "/") + fileName);
            ExcelHelper excel_helper = new ExcelHelper(context.Server.MapPath("~/UploadFile/" + Folder + "/") + fileName);
            DataTable dt = excel_helper.ExcelToDataTable("", true);
            LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
            Dictionary<string, string> dic = JsonToDict.GetDicByJsonFile(context.Server.MapPath("~/json/" + jsonfile));
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dic.ContainsKey(dt.Columns[i].ColumnName))
                {
                    dt.Columns[i].ColumnName = dic[dt.Columns[i].ColumnName];
                }
            }
            var reflist = ModelConvertHelper.GetListByObject<T>(dt);
            return reflist;
        }
    }
}